package com.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.server.config.security.JwtTokenUtils;
import com.server.pojo.Admin;
import com.server.mapper.AdminMapper;
import com.server.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.server.pojo.ResponseBean;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author SongHL
 * @since 2025-09-13
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private UserDetailsService userDetailsService;

    //安全框架提供的加密算法
    @Autowired
    private PasswordEncoder passwordEncoder;

    //jwt,生成token
    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    //token的头部信息
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    //调用mapper
    @Autowired
    private AdminMapper adminMapper;

    /**
     * 登录之后返回token
     * @author SongHL
     * @date 2025/9/13 15:27
     * @param username
     * @param password
     * @param request
     * @return com.server.pojo.ResponseBean
     */
    @Override
    public ResponseBean login(String username, String password, HttpServletRequest request){

        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if(userDetails == null || !passwordEncoder.matches(password,userDetails.getPassword())){
            return ResponseBean.error("用户名或密码不正确!");
        }
        if(!userDetails.isEnabled()){
            return ResponseBean.error("账号被禁用，请联系管理员!");
        }
        //更新登录用户对象
        //1.封装Authentication对象
        UsernamePasswordAuthenticationToken authenticationTokens =
                new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());

        //设置当前用户认证信息的核心操作，作用是将用户的认证状态存入安全上下文，让后续的程序能识别 “当前登录的是谁”
        SecurityContextHolder.getContext().setAuthentication(authenticationTokens);

        //生成token
        String token = jwtTokenUtils.generateToken(userDetails);
        Map<String,String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);

        //给前端，让前端放在请求头里面的
        //则前端会收到格式为 tokenHead token
        return ResponseBean.success("登录成功",tokenMap);
    }

    /**
     * 根据用户名获取用户信息
     * @author SongHL
     * @date 2025/9/13 15:52
     * @param username
     * @return com.server.pojo.Admin
     */
    @Override
    public Admin getAdminByUsername(String username) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",username)
                .eq("enable",true));
    }
}
